package Offer;

/**
 * 二叉搜索树与双向链表
 * @author 是阿秋啊
 * @date 2022/04/14 20:04
 **/
public class Num36dfsRootGoDoubLink {
    public NodeRoot treeToDoublyList(NodeRoot root) {
        if (root == null) {
            return null;
        }
        NodeRoot head = dfs(root);
        NodeRoot tail = head;
        while (tail.right != null) {
            tail = tail.right;
        }
        tail.right = head;
        head.left = tail;
        return head;
    }

    private NodeRoot dfs(NodeRoot root) {
        if (root == null) {
            return root;
        }
        NodeRoot leftHead = dfs(root.left);
        NodeRoot leftTail = leftHead;
        while (leftTail != null && leftTail.right != null) {
            leftTail = leftTail.right;
        }
        if (leftTail != null) {
            leftTail.right = root;
            root.left = leftTail;
        }
        NodeRoot rightHead = dfs(root.right);
        if (rightHead != null) {
            rightHead.left = root;
            root.right = rightHead;
        }
        return leftHead == null ? root : leftHead;
    }
}
class NodeRoot {
    public int val;
    public NodeRoot left;
    public NodeRoot right;

    public NodeRoot() {}

    public NodeRoot(int _val) {
        val = _val;
    }

    public NodeRoot(int _val,NodeRoot _left,NodeRoot _right) {
        val = _val;
        left = _left;
        right = _right;
    }
}
